package com.youlu.myapplication.test;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * @author : YOULU  sym
 * date   : 2020/11/30 0030
 * desc   :
 */
public class ScrollerView extends View {

    private Scroller scroller;

    public ScrollerView(Context context) {
        super(context);
        initView(context);
    }

    public ScrollerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ScrollerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public void initView(Context context) {

        setBackgroundColor(Color.GREEN);
        scroller = new Scroller(context);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();

        //判断Scroller是否执行完没。
        if (scroller.computeScrollOffset()) {
            int currX = scroller.getCurrX();
            int currY = scroller.getCurrY();

            Log.i("ScrollerView", " currX : " + currX + " currY : " + currY);
            //记住Scroller的滑动当前坐标。
            ((View) getParent()).scrollTo(scroller.getCurrX(), scroller.getCurrY());
            //不停的绘制
            invalidate();
        }
    }

    int lastX;
    int lastY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        //        int x = (int) event.getX();
        //        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getX();
                lastY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:

                int offsetX = (int) event.getX() - lastX;
                int offsetY = (int) event.getY() - lastY;

                ((View) getParent()).scrollBy(-offsetX, -offsetY);
                break;
            case MotionEvent.ACTION_UP:
                //手指离开时，执行滑动过程
                View viewGroup = (View) getParent();

                scroller.startScroll(viewGroup.getScrollX(), viewGroup.getScrollY(), -viewGroup.getScrollX(), -viewGroup.getScrollY(), 5000);

                invalidate();
                break;
            default:
                break;
        }
        return true;
    }

}
